#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
This file is part of playlistbs.

@author: Romain RICHARD
@contact: romain.richard.IT.engineer@gmail.com
@version: 2.0
@copyright: GPLv3

@change: 2012-09-17: Used pylint to clean up the code
@change: 2011-08-05: Added shows_search_url, shows_add_url
@change: 2011-08-01: Creation of the file
"""

import sys

from urllib import urlencode
from urllib2 import urlopen, URLError
from xml.dom.minidom import parseString


class API(object):
    """Class using the BetaSeries' API.

    Public functions:
    set_token -- Configure the member's token.

    create_request -- Create a request.

    send_request -- Send a request to the API.

    """

    api_url = "https://api.betaseries.com/"
    members_auth_url = api_url + "members/auth.xml"
    members_downloaded_url = api_url + "members/downloaded/"
    members_episodes_all_url = api_url + "members/episodes/all.xml"
    members_infos_url = api_url + "members/infos.xml"
    members_watched_url = api_url + "members/watched/"
    shows_add_url = api_url + "shows/add/"
    shows_search_url = api_url + "shows/search.xml"
    subtitles_show_url = api_url + "subtitles/show.xml"

    def __init__(self, key):
        """Constructor.

        @type key: String
        @param key: The developper's key

        """
        self.key = key
        self.token = ""

    def set_token(self, token):
        """Configure the member's token.

        @type token: String
        @param token: Member's token

        """
        self.token = token

    def create_request(self, url, variables=None):
        """Create a request.

        @type url: String
        @param url : URL of the API

        @type variables: Dictionary
        @param variables: Variables to add (default: None)

        @rtype: String
        @return: The request url

        """
        if not variables:
            variables = {}
        url += "?{param}".format(param=urlencode({"key": self.key}))
        url += "&{param}".format(param=urlencode({"token": self.token}))
        for key, value in variables.items():
            url += "&{param}".format(param=urlencode({key: value}))
        return url

    def send_request(self, url, variables=None):
        """Send a request to the API.

        @type url: String
        @param url : URL of the API

        @type variables: Dictionary
        @param variables: Variables to add (default: None)

        @rtype: Document
        @return: A Document containing the result of the request

        """
        if not variables:
            variables = {}
        url = self.create_request(url, variables)
        try:
            data = urlopen(url).read()
        except URLError, err:
            print(err)
            sys.exit(2)
        xml = parseString(data)
        return xml
